package com.ruizhong.remotehelper.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;

import androidx.annotation.NonNull;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;

public class ZoomableSurfaceView extends SurfaceView implements SurfaceHolder.Callback, ScaleGestureDetector.OnScaleGestureListener {
    private final ScaleGestureDetector scaleGestureDetector;
    private float scaleFactor = 1.0f; // 初始缩放级别
    private String aimIp = null;
    public WebSocket ws = null;
    private int left = 0;
    private int top = 0;
    private int middleLeft = 0;
    private int middleTop = 0;
    private Float lastX = null;
    private Float lastY = null;
    private Canvas canvas = null;
    private Bitmap bitmap = null;
    private float newWidth = 0;
    private float newHeight = 0;
    private int screenWidth = 0;
    private int screenHeight = 0;
    private SurfaceHolder surfaceHolder = null;

    public ZoomableSurfaceView(Context context, AttributeSet attributeSet) {
        super(context, attributeSet);
        getHolder().addCallback(this);
        surfaceHolder = getHolder();
        scaleGestureDetector = new ScaleGestureDetector(context, new ScaleListener());
    }


    public void setParam(String aimIp, int screenWidth, int screenHeight) {
        this.aimIp = aimIp;
        this.screenWidth = screenWidth;
        this.screenHeight = screenHeight;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        scaleGestureDetector.onTouchEvent(event);
        return true; // 返回true表示事件已经被处理  
    }

    @Override
    public boolean onScale(@NonNull ScaleGestureDetector detector) {
        scaleFactor *= detector.getScaleFactor();
        scaleFactor = Math.max(0.1f, Math.min(scaleFactor, 5.0f)); // 限制缩放范围
//        updateScaleFactor(); // 更新渲染器的缩放级别
        return true;
    }

    public float getScaleFactor() {
        return scaleFactor;
    }

    @Override
    public boolean onScaleBegin(@NonNull ScaleGestureDetector detector) {
        return false;
    }

    @Override
    public void onScaleEnd(@NonNull ScaleGestureDetector detector) {

    }

    private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
        @Override
        public boolean onScale(ScaleGestureDetector detector) {
            System.out.println("监听到缩放");
            scaleFactor *= detector.getScaleFactor();
            // 限制缩放级别，防止过大或过小  
            scaleFactor = Math.max(0.1f, Math.min(scaleFactor, 10.0f));
            newWidth = Math.round(bitmap.getWidth() * scaleFactor);
            if (newWidth < screenWidth) {
                newWidth = screenWidth;
                newHeight = bitmap.getHeight() / ((float) bitmap.getWidth() / screenWidth);
                left=middleLeft;
                top=middleTop;
            } else {
                newHeight = Math.round(bitmap.getHeight() * scaleFactor);
            }
            // 通知渲染线程更新  
            // 这可能需要通过Handler或其他同步机制来完成  
            return true;
        }
    }

    // SurfaceHolder.Callback实现...
    @Override
    public void surfaceCreated(@NonNull final SurfaceHolder holder) {
        String localIp = null;
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                        localIp = inetAddress.getHostAddress();
                    }
                }
            }
        } catch (SocketException ex) {
            Log.e("BaseScanTvDeviceClient", "获取本机IP false =" + ex.toString());
        }
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("ws://" + aimIp + ":8080/wsServer/" + localIp)
                .build();


        WebSocketListener listener = new WebSocketListener() {
            @Override
            public void onOpen(WebSocket webSocket, Response response) {
                // 连接打开时的回调
                webSocket.send("Hello, WebSocket!");
            }

            @Override
            public void onMessage(WebSocket webSocket, ByteString bytes) {
                // 收到消息时的回调
                byte[] screenByte = bytes.toByteArray();
                bitmap = BitmapFactory.decodeByteArray(screenByte, 0, screenByte.length);
                if (bitmap == null) {
                    return;
                }
                if (newHeight == 0 && newWidth == 0) {
                    newWidth = screenWidth;
                    newHeight = bitmap.getHeight() / ((float) bitmap.getWidth() / screenWidth);
                    left = (int) ((screenWidth - newWidth) / 2);
                    top = (int) ((screenHeight - newHeight) / 2);
                    middleLeft=left;
                    middleTop=top;
                }
                canvas = holder.lockCanvas();
                if (canvas != null) {
                    Paint paint = new Paint();
                    canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
                    canvas.drawBitmap(
                            bitmap,
                            new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()),
                            new Rect(left, top, (int) (left + newWidth), (int) (top + newHeight)),
                            paint);
                }
                holder.unlockCanvasAndPost(canvas);
//                bitmap.recycle();
            }

            @Override
            public void onFailure(WebSocket webSocket, Throwable t, Response response) {
                // 连接失败时的回调
                t.printStackTrace();
            }
        };
        ws = client.newWebSocket(request, listener);

        this.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int pointerCount = event.getPointerCount();

                float x = event.getRawX();
                float y = event.getRawY();
                System.out.println("触控点共"+pointerCount+"个，x="+x+",y="+y);
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        System.out.println("监听到触屏");
                        lastX = x;
                        lastY = y;
                        ws.send(new UserEvent(0, x - left, y - top, (int) newWidth, (int) newHeight).toString());
                        break;
                    case MotionEvent.ACTION_MOVE:
                        if (pointerCount==2 && (newWidth > screenWidth || newHeight > screenHeight)) {
                            if ((x-lastX>0&&left<0)||(x-lastX<0&&(left+newWidth)>screenWidth)){
//                                向右/左平移
                                left+=(x-lastX);
                            }
                            if ((y-lastY>0&&top<0)||(y-lastY<0&&(top+newHeight)>screenHeight)){
//                                向下/上平移
                                top+=(y-lastY);
                            }
                            lastX = x;
                            lastY = y;
                            canvas = holder.lockCanvas();
                            if (canvas != null) {
                                Paint paint = new Paint();
                                canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
                                canvas.drawBitmap(
                                        bitmap,
                                        new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()),
                                        new Rect(left, top, (int) (left + newWidth), (int) (top + newHeight)),
                                        paint);
                            }
                            holder.unlockCanvasAndPost(canvas);
                }
                        if (pointerCount==1){
                            ws.send(new UserEvent(5,x-left,y-top,(int)newWidth,(int)newHeight).toString());
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        UserEvent userEvent = new UserEvent(4);
                        ws.send(userEvent.toString());
                        System.out.println("监听到触摸离开");
                        break;
                }
                return false;
            }
        });
        this.setOnKeyListener(new View.OnKeyListener(){
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                System.out.println(keyCode);
                return false;
            }
        });
    }

    @Override
    public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {
    }

    @Override
    public void surfaceDestroyed(@NonNull final SurfaceHolder holder) {
    }
}